<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";

if ($login['username'] == "")
{
  header ("location: ./");
  exit;
}

$connection = db_open ();

/* Create the XML feed */
if (isset ($_POST['tid']))
{
  $templatename = mysql_real_escape_string (htmlentities (trim ($_POST['templatename']), ENT_COMPAT, "UTF-8", false));
  $templatelayout = trim ($_POST['templatelayout']);
  $template = "<template>";
  
  $fieldcount = $_POST['fieldcount'];
  $n = 1;
  while ($n <= $fieldcount)
    {
      $type = "type$n";
      $name = "name$n";
      $label = "label$n";
      $delfield = "delfield$n";
      if (!isset ($_POST[$delfield]))
        $template .= "<field type=\"".trim ($_POST[$type])."\" name=\"".trim ($_POST[$name])."\" label=\"".trim ($_POST[$label])."\" />";
      $n++;
    }
  
  if (isset ($_POST['addfield']))
    $template .= "<field type=\"text\" name=\"field$n\" label=\"Field$n\" />";
  
  $template .= "</template>";
  
  /* Now update the template in the database */
  mysql_query ("UPDATE ".db_maketablename ($table_templates)." SET name='$templatename', fields='".mysql_real_escape_string ($template)."', xslt='$templatelayout' WHERE id='{$_POST['tid']}'");
  
   /* Add a new style? */
  $now = time ();
  if (isset ($_POST['addstyle']))
    mysql_query ("INSERT INTO ".db_maketablename ($table_styles_rel)." (style_id, template_id, identifier, linked) VALUES ('0', '{$_POST['tid']}', 'style_$now', '1')");
  
  /* Process styles */
  $stylecount = $_POST['stylecount'];
  $n = 1;
  while ($n <= $stylecount)
    {
      $name = "style_name$n";
      $identifier = "style_identifier$n";
      $identifier_s = mysql_real_escape_string (trim ($_POST[$identifier]));
      $linked = "style_linked$n";
      $id = "style_id$n";
      $delstyle = "delstyle$n";
      if (isset ($_POST[$delstyle]))
        mysql_query ("DELETE FROM ".db_maketablename ($table_styles_rel)." WHERE id='{$_POST[$id]}'");
      else
        mysql_query ("UPDATE ".db_maketablename ($table_styles_rel)." SET style_id='{$_POST[$name]}', identifier='$identifier_s', linked='{$_POST[$linked]}' WHERE id='{$_POST[$id]}'");
      $n++;
    }
}

db_close ($connection);
header ("location:$app_adminpath/?p=templates&tid={$_POST['tid']}&show={$_POST['show']}");
exit;
?>
